import Apple from './Apple'
import { action, computed,  makeObservable, observable, runInAction } from 'mobx'

export default class AppleStore{
  constructor () {
    this.apples = []
    this.eatedApples = []
    this.isPicking = false
    makeObservable(this,{
      apples:observable,
      eatedApples:observable,
      isPicking:observable,
      add:action.bound,
      eat:action.bound,
      notEatenWeight:computed,
      EatenWeight:computed,
    })
  }

  async add(){
    this.isPicking = true
    try{
      const ret = await this.pickApple()
      if(ret===1){
        runInAction(()=>{
          this.apples.push(new Apple(this.genId()))
          this.isPicking = false
        })
      }
    }catch (e){
      console.log(e)
      runInAction(()=>{
        this.isPicking = false
      })
    }
  }

  eat(id){
    const targetIdx = this.apples.findIndex(apple=>apple.id===id)
    if(targetIdx>=0){
      this.eatedApples.push(this.apples.splice(targetIdx,1)[0])
    }else{
      alert('id is not exist')
    }

  }

  get notEatenWeight(){
    return this.apples.reduce((total,apple)=>(total+apple.weight),0)
  }
  get EatenWeight(){
    return this.eatedApples.reduce((total,apple)=>(total+apple.weight),0)
  }

  genId(){
    if(this.apples.length<1){
      return 1
    }
    return (this.apples[this.apples.length-1]).id+1
  }

  pickApple(){
    return new Promise(resolve => {
      setTimeout(()=>{resolve(1)},800)
    })
  }

}
